package com.teach.demo03;


import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class Server {
	
	public static Map<String, Socket> map = Collections.synchronizedMap(new HashMap<>());

	public static void main(String[] args) {
		ServerSocket server = null;
		try {
			server = new ServerSocket(8888);

			while(true){
				Socket client=server.accept();
				new Thread(()->{
					doOne(client);
				}).start();
			}

	

		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	public static void doOne(Socket client){		
		try{
			String id = client.getInetAddress().getHostAddress();
			map.put(id, client);
			System.out.println("连接了客户端："+id);
			InputStream in1 = client.getInputStream();
			DataInputStream in = new DataInputStream(in1);
			while (true) {
				try {
					String str = in.readUTF();
					String regex = "^@(\\d+\\.\\d+\\.\\d+\\.\\d+) (.*)$";
					if(str.matches(regex)){
						String ip = str.replaceAll(regex, "$1");
						String msg = str.replaceAll(regex, "$2");
						System.out.println("["+id+"]悄悄的对["+ip+"]说: "+str);
						
						try{
							DataOutputStream out = new DataOutputStream(map.get(ip).getOutputStream());
							out.writeUTF("["+id+"]悄悄对你说: "+str);
						}catch(Exception ex){
						}
					}else{
						System.out.println("["+id+"]大声说: "+str);
						for(Socket s : map.values()){
							try{
								DataOutputStream out = new DataOutputStream(s.getOutputStream());
								out.writeUTF("["+id+"]: "+str);
							}catch(Exception ex){
							}
						}
					}
				} catch (Exception e) {
					break;
				}
			}

			map.remove(id);
			try{
				client.close();
			}catch(Exception e){}
			System.out.println("连接关闭："+id);
			
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
}